/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.anism.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.anism.API.HolidayInputLocal;
import org.anism.API.HolidayValidationLocal;
import org.anism.entity.Employee;
import org.anism.entity.HolidayRequest;

/**
 *
 * @author user
 */
@WebServlet(name = "ValidateHolidayRequestServlet", urlPatterns = {"/ValidateHolidayRequestServlet"})
public class ValidateHolidayRequestServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        boolean isAuthenticated = false;
        boolean hasFailedLogin = false;
        Employee emp = null;
        HolidayValidationLocal holidayValidation = null;

        // Lookup HolidayInput session bean
        try {
            Context jndiContext = new InitialContext();
            holidayValidation = (HolidayValidationLocal) jndiContext.lookup("java:global/Holidays2-war/HolidayValidation!org.anism.API.HolidayValidationLocal");
        } catch (NamingException ex) {
            Logger.getLogger(ValidateHolidayRequestServlet.class.getName()).log(Level.SEVERE, "Unable to lookup session bean", ex);
        }

        // Check if user is logged in
        if (request.getSession(true).getAttribute("user.authenticated") != null) {
            isAuthenticated = true;
        } else {
            String login = request.getParameter("login");
            String password = request.getParameter("password");

            // Check if user has completed the  authentication form
            if (login != null && password != null) {
                emp = holidayValidation.authenticate(login, password);

                if (emp != null) {
                    request.getSession().setAttribute("user.authenticated", true);
                    request.getSession().setAttribute("user.firstname", emp.getFirstName());
                    request.getSession().setAttribute("user.lastname", emp.getLastName());
                    request.getSession().setAttribute("user.id", emp.getEmployeeId());
                    isAuthenticated = true;
                } else {
                    hasFailedLogin = true;
                }
            }
        }

        if (!isAuthenticated) { // user is not logged in, display authentication form
            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Authentication</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Authentication</h1>");

                if (hasFailedLogin) {
                    out.println("<p>Authentication failed, please try again</p>");
                }
                out.println("<form action=\"./ValidateHolidayRequestServlet\" method=\"post\" >");
                out.println("Login : <input type=\"text\" name=\"login\"/><br />");
                out.println("Password : <input type=\"text\" name=\"password\" /><br />");
                out.println("<input type=\"submit\" value=\"Submit\" />");
                out.println("</form>");
                out.println("<p><a href=\"index.jsp\" >Go back to menu</a></p>");
                out.println("</body>");
                out.println("</html>");
            } finally {
                out.close();
            }
        } else { // user is authenticated
//            Date today = GregorianCalendar.getInstance().getTime();
//            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

            // If a request is selected for validation
            if(request.getParameter("idRequest") != null) {
                Integer id = Integer.parseInt(request.getParameter("idRequest"));
                HolidayRequest hRequest = holidayValidation.getHolidayRequest(id);
                if(holidayValidation.validateRequest(hRequest) == false) {
                    Logger.getLogger(ValidateHolidayRequestServlet.class.getName()).log(Level.SEVERE, "Failed to validate request");
                    out.println("<p style=\"color:red;\">Failed to validate request</p>");
                } else
                    out.println("<p>Request validated</p>");
            }
            
            String employeeId = (String) request.getSession().getAttribute("user.id");

            if (employeeId != null) {
                
            }

            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Validate holiday requests</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<p>You are logged in as "
                        + request.getSession().getAttribute("user.id")
                        + " - <a href=\"signout.jsp\" >sign out</a>"
                        + "</p>");
                out.println("<h1>Validate holiday requests</h1>");
                out.println("<p>Firstname : " + request.getSession().getAttribute("user.firstname") + "<br />");
                out.println("Lastname : " + request.getSession().getAttribute("user.lastname") + "</p>");
               
                // TODO : for each employee managed by me, display holiday requests
                Collection<HolidayRequest> hReqs = holidayValidation.getAllHolidayRequests(employeeId);
                out.println("<table border=1>");
                out.println("<tr><th>Start</th><th>End</th><th>Current status</th><th>Employee</th><th></th></tr>");
                for(HolidayRequest hr : hReqs) {
                    out.println("<tr><td>"+hr.getStartDate()+"</td><td>"+hr.getEndDate()+"</td><td>"+hr.getCurrentStatus()+"</td><td>"+hr.getOwner().getEmployeeId()+"</td><td><a href=\"./ValidateHolidayRequestServlet?idRequest="+hr.getId()+"\">Validate</a></td></tr>");
                }
                out.println("</table>");
                
                out.println("<p><a href=\"index.jsp\" >Go back to menu</a></p>");
                out.println("</body>");
                out.println("</html>");
            } finally {
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
